﻿#include "stdafx.h"
#include "BlockContext.h"
#include "AutoType.h"
#include "AstFunction.h"
#include "CodeGenerate/CodeGen.h"

CodeGen * BlockContext::findSymbolValue(const std::string & name, bool recursive)
{
	auto i = _symbols.find(name);
	if (i != _symbols.end()) {
		return i->second;
	}
	else if (recursive && parent) {
		return parent->findSymbolValue(name, true);
	}
	return nullptr;
}

void BlockContext::setSymbolValue(const std::string & name, CodeGen * v)
{
	auto i = _symbols.find(name);
	if (i != _symbols.end()) {
		AstType* type = i->second->type;
		if (!dynamic_cast<AutoType*>(type))
			throw std::runtime_error("重复的符号：" + name);
	}

	_symbols[name] = v;
}

BlockGen * BlockContext::createGen(SiContext * context, std::vector<AstNode*> lines, const std::string & name)
{
	auto* block = new BlockGen();
	block->name = name;
	auto bc = new BlockContext(context);
	for (auto c : lines) {
		auto*g = c->makeGen(bc);
		block->codes.push_back(g);
	}
	return block;
}

